package com.xjgz.aio.socket.pro.extension.protocol;

import com.xjgz.aio.socket.Protocol;
import com.xjgz.aio.socket.transport.AioSession;

import java.nio.ByteBuffer;

public abstract class FixedLengthBytesProtocol<T> implements Protocol<T> {

    @Override
    public T decode(ByteBuffer readBuffer, AioSession session) {
        if (readBuffer.remaining() < Integer.BYTES) {
            return null;
        }
        readBuffer.mark();
        int length = readBuffer.getInt();
        if (readBuffer.remaining() < length) {
            readBuffer.reset();
            return null;
        }
        byte[] bytes = new byte[length];
        readBuffer.get(bytes);
        return decode(bytes, session);
    }

    protected abstract T decode(byte[] bytes, AioSession session);
}
